﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace VBAConvertor.Parsers
{
    public class WordReplacementParser : ILineParser
    {
        private static readonly Regex _WordOp =
            new Regex(
                @"\b(?<word>\w+)\b",
                RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.Singleline);

        private static readonly Dictionary<string, string> _WordDict;
 
        static WordReplacementParser()
        {
            _WordDict = new Dictionary<string, string>();
            _WordDict["True"] = "true";
            _WordDict["False"] = "false";
            _WordDict["vbOKCancel"] = "MessageBoxButtons.OKCancel";
            _WordDict["vbOKOnly"] = "MessageBoxButtons.OK";
            _WordDict["vbAbortRetryIgnore"] = "MessageBoxButtons.AbortRetryIgnore";
            _WordDict["vbYesNoCancel"] = "MessageBoxButtons.YesNoCancel";
            _WordDict["vbYesNo"] = "MessageBoxButtons.YesNo";
            _WordDict["vbRetryCancel"] = "MessageBoxButtons.RetryCancel";
        }

        public string Parse(Stack<ParseStatus> statuses, string lineContent, LinesReader reader, out bool success, ref bool lineClosed)
        {
            success = _WordOp.IsMatch(lineContent);
            if (!success) return lineContent;
            return _WordOp.Replace(lineContent, match =>
                {
                    if (match.Success)
                    {
                        if (_WordDict.ContainsKey(match.Groups["word"].Value))
                        {
                            return _WordDict[match.Groups["word"].Value];
                        }
                        return match.Value;
                    }
                    throw new Exception();
                });
        }
    }
}
